//
//  StadiumDetailInfoView.m
//  GolfFriend
//
//  Created by Vescky on 14-3-1.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "StadiumDetailInfoView.h"
#import "MJRefresh.h"
#import "AppsEngine.h"
#import "DXAlertView.h"
#import "SVProgressHUD.h"
#import "UserSession.h"
#import "LitePhotoCollectionView.h"
#import "UIImageView+MJWebCache.h"
#import "DateUtility.h"
#import "CommonUtility.h"
#import "ZanDao.h"
#import "CircleCommentCell.h"
//#import "StadiumNavViewController.h"
#import "BMapNavigationViewController.h"
#import "AppsLocationManager.h"

@interface StadiumDetailInfoView ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,MJRefreshBaseViewDelegate> {
    NSMutableArray *commentArray;
    
    CircleCommentCell *sampleCell;
    
    //下拉刷新，上拉加载更多
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    
    int currentPage;
    CGRect rectInput;
    
    //内容区域
    LitePhotoCollectionView *photosView;
    UILabel *labelContent;
    
    UIButton *btnHideKeyboard;
}
@end

@implementation StadiumDetailInfoView
@synthesize stadiumInfo,isSupported,stadiumId,coverImage;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitle:@"球场详情"];
    [super customBackButton];
    [self initView];
    [self initData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initView {
    //清除定位图层
    [[AppsLocationManager sharedManager] destoyMapView];
    
    
    //初始化刷新view
    _header = [MJRefreshHeaderView header];
    _header.scrollView = staduimScrollView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.scrollView = staduimScrollView;
    _footer.delegate = self;
    
//    //监听键盘高度的变换
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//    
//    // 键盘高度变化通知，ios5.0新增的
//#ifdef __IPHONE_5_0
//    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
//    if (version >= 5.0) {
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
//    }
//#endif

}

- (void)initData {
    currentPage = 1;
    
    if (!stadiumInfo) {
        return;
    }
    
    stadiumId = [stadiumInfo objectForKey:@"id"];
    commentArray = [[NSMutableArray alloc] init];
    
    labelTitle.text = [stadiumInfo objectForKey:@"name"];
    labelComment.text = [stadiumInfo objectForKey:@"comment"];
    labelZan.text = [stadiumInfo objectForKey:@"zan"];
    
    //-----  set content label
    float marginForContent = 5.0;
    float fontSizeForContent = 15.0;
    float imageHeight = 150.0;
    
    //-----  set photos collection
    NSArray *imgArr = [[stadiumInfo objectForKey:@"picLink"] objectForKey:@"image"];
    if (imgArr && [imgArr count] > 0) {
        photosView = [[LitePhotoCollectionView alloc] init];
        [photosView setPhotoCollection:[[NSMutableArray alloc] initWithArray:imgArr]];
        [photosView setMargin: 2.0];
        [photosView setViewWidth:viewContent.frame.size.width];//与content同宽度
        [photosView setColCount:1];
        [photosView setScaleHDW:(float)imageHeight/320.0];
        [photosView.view setFrame:CGRectMake(0,
                                             marginForContent,
                                             viewContent.frame.size.width - 2 * marginForContent,
                                             imageHeight * [imgArr count])];
        [viewContent addSubview:photosView.view];
    }
    
    //set describe
    NSString *contentString = [stadiumInfo objectForKey:@"describe"];
    CGSize cSize = [contentString sizeWithFont:[UIFont systemFontOfSize:fontSizeForContent] constrainedToSize:CGSizeMake(viewContent.frame.size.width - 2 * marginForContent,1000) lineBreakMode:0];
    labelContent = [[UILabel alloc] initWithFrame:CGRectMake(marginForContent,
                                                             photosView.view.frame.origin.y + photosView.view.frame.size.height + marginForContent,
                                                             viewContent.frame.size.width - 2 * marginForContent,
                                                             cSize.height )];
    [labelContent setLineBreakMode:0];
    [labelContent setNumberOfLines:0];
    [labelContent setText:contentString];
    [labelContent setFont:[UIFont systemFontOfSize:fontSizeForContent]];
    [labelContent setBackgroundColor:[UIColor clearColor]];
    [viewContent addSubview:labelContent];
    
    UILabel *labelPrice = [[UILabel alloc]initWithFrame:CGRectMake(0, labelContent.frame.origin.y + labelContent.frame.size.height + marginForContent, viewContent.frame.size.width - 2 * marginForContent, 30)];
    labelPrice.text = [NSString stringWithFormat:@"%@%@",[stadiumInfo objectForKey:@"price"],[stadiumInfo objectForKey:@"unit"]];
    labelPrice.textAlignment = NSTextAlignmentRight;
    labelPrice.font = [UIFont systemFontOfSize:17.0];
    [viewContent addSubview:labelPrice];
    
    CGRect cRect = viewContent.frame;
    cRect.size.height = labelPrice.frame.origin.y + labelPrice.frame.size.height + 2 * marginForContent;
    [viewContent setFrame:cRect];
    
    CGRect toolbarRect = viewToolbar.frame;
    toolbarRect.origin.y = cRect.origin.y + cRect.size.height;
    [viewToolbar setFrame:toolbarRect];
    
    CGRect clRect = tbCommentList.frame;
    clRect.origin.y = toolbarRect.origin.y + toolbarRect.size.height + 2 * marginForContent;
    [tbCommentList setFrame:clRect];
    
    [staduimScrollView setContentSize:CGSizeMake(staduimScrollView.frame.size.width, clRect.origin.y + clRect.size.height - 65)];
    
    [self getCommentData];
    
    NSDictionary *dictZ = [[NSDictionary alloc] initWithObjectsAndKeys:[[UserSession shareUserSession] getUserId],@"userId",@"stadium",@"type",stadiumId,@"recordId", nil];
    isSupported = [[ZanDao shareZanDao] checkIfZaned:dictZ];
    [btnZan setSelected:isSupported];
}


- (void)enableAnimating:(bool)_enable {
    if (_enable) {
        [viewLoadingComment setFrame:CGRectMake(0, viewToolbar.frame.origin.y + viewToolbar.frame.size.height + 20, staduimScrollView.frame.size.width, 100)];
        [staduimScrollView addSubview:viewLoadingComment];
        [clActivityIndicator startAnimating];
    }
    else {
        [viewLoadingComment removeFromSuperview];
        [clActivityIndicator stopAnimating];
    }
}

//获取Cell的高度
- (float)getCellHeightWithContent:(NSDictionary*)_dict {
    if (!sampleCell) {
        sampleCell = [[[NSBundle mainBundle] loadNibNamed:@"CircleCommentCell" owner:self options:nil] objectAtIndex:0];
    }
    return [sampleCell getContentHeight:_dict];
}

- (IBAction)btnAction:(id)sender {
    UIButton *btn = (UIButton*)sender;
    if (btn.tag == 100) {
        //唤出评论
        
    }
    else if (btn.tag == 101) {
        //点赞
        if (isSupported) {
            [SVProgressHUD showErrorWithStatus:@"您已赞过!"];
            return;
        }
        NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:stadiumId,@"articleId",@"stadium",@"type", nil];
        [[AppsEngine shareAppsEngine] submitRequest:@"gfPublishZan" param:params onCompletion:^(id jsonResponse) {
            NSLog(@"zan success");
        } onError:^(NSError *error) {
            
        } method:@"GET"];
        
        //缓存到本地
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[[UserSession shareUserSession] getUserId],@"userId",
                              @"stadium",@"type",stadiumId,@"recordId",nil];
        [[ZanDao shareZanDao] saveZanInfo:dict];
        isSupported = YES;
        labelZan.text = [NSString stringWithFormat:@"%d",[labelZan.text intValue]+1];
        [btnZan setSelected:YES];
        
        [stadiumInfo setObject:labelZan.text forKey:@"zan"];
        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Stadium_Comment_Published object:stadiumInfo];
    }
    else if (btn.tag == 102) {
        //进入导航
        BMapNavigationViewController *navVc = [[BMapNavigationViewController alloc] init];
        navVc.stadiumInfo = stadiumInfo;
        [self.navigationController pushViewController:navVc animated:YES];
    }
    else if (btn.tag == 103) {
        //发送评论
        if ([self checkForm]) {
            NSLog(@"发送评论，刷新评论列表，隐藏键盘");
            NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:stadiumId,@"stadiumId",[[UserSession shareUserSession] getUserId],@"fromId",tfComment.text,@"content", nil];
            [[AppsEngine shareAppsEngine] submitRequest:@"gfPublishStadiumComment" param:params onCompletion:^(id jsonResponse) {
                NSLog(@"comment success");
            } onError:^(NSError *error) {
                
            } method:@"GET"];
            labelComment.text = [NSString stringWithFormat:@"%d",[[stadiumInfo objectForKey:@"comment"] intValue] + 1];
            [stadiumInfo setObject:labelComment.text forKey:@"comment"];
            [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Stadium_Comment_Published object:stadiumInfo];
            [tfComment resignFirstResponder];
            tfComment.text = @"";
        }
    }

}


- (void)refreshTableView {
    if (!commentArray || [commentArray count] < 1) {
        if (currentPage <= 1) {
            [self showNoCommentView];//第一次请求，没有数据就显示无数据view
        }
    }
    else {
        [tbCommentList setHidden:NO];
        [tbCommentList reloadData];
        currentPage++;//评论页码加一
        float tbHeight = [self getTableViewHeightWithDataArray:commentArray];
        CGRect tbRect = tbCommentList.frame;
        tbRect.size.height = tbHeight;
        [tbCommentList setFrame:tbRect];
        [staduimScrollView setContentSize:CGSizeMake(staduimScrollView.contentSize.width, tbRect.origin.y + tbRect.size.height + 20)];
    }
}

- (float)getTableViewHeightWithDataArray:(NSArray*)_arr {
    if (!_arr || [_arr count] <= 0) {
        _arr = commentArray;//默认参数
    }
    float tbHeight = 0;
    for (int i = 0; i < [_arr count]; i++) {
        tbHeight = tbHeight + [self getCellHeightWithContent:[_arr objectAtIndex:i]];
    }
    //无数据，返回无数据的高度
    if (tbHeight <= 0) {
        return 0;
    }
    return tbHeight;
}

- (void)getCommentData {
    if (currentPage <= 1) {
        [self enableAnimating:YES];
    }
    
    //网上请求数据
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",currentPage],@"page",
                                stadiumId,@"stadiumId", nil];
    [[AppsEngine shareAppsEngine] submitRequest:@"gfGetStadiumComments" param:dict onCompletion:^(id jsonResponse) {
        if (currentPage <= 1) {
            [self enableAnimating:NO];
            [viewNoComment removeFromSuperview];
        }
        
        if ([[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            NSLog(@"刷新成功");
            NSMutableArray *commentArr = [jsonResponse objectForKey:@"content"];
            commentArray = [self combileArray:commentArray withArray:commentArr];
            [self refreshTableView];
        }
        
    } onError:^(NSError *error) {
        NSLog(@"联网失败");
        if (currentPage <= 1) {
            [self enableAnimating:NO];
        }
//        DXAlertView *dAlert = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"暂无网络连接!无法获取评论!" leftButtonTitle:nil rightButtonTitle:@"确定"];
//        [dAlert show];
        [self showNoCommentView];
    } method:@"GET"];
}

- (NSMutableArray*)combileArray:(NSMutableArray*)arr1 withArray:(NSMutableArray*)arr2 {
    if (!arr1 || ![arr1 respondsToSelector:@selector(count)]) {
        return arr2;
    }
    if (!arr2 || ![arr2 respondsToSelector:@selector(count)]) {
        return arr1;
    }
    
    for (int i = 0; i < [arr2 count]; i++) {
        [arr1 addObject:[arr2 objectAtIndex:i]];
    }
    return arr1;
}

- (bool)checkForm {
    if ([tfComment.text length] < 1) {
        [SVProgressHUD showErrorWithStatus:@"评论内容不能为空!"];
        return NO;
    }
    return YES;
}

- (void)showNoCommentView {
    [tbCommentList setHidden:YES];
    CGRect nRect = viewNoComment.frame;
    nRect.origin.y = viewToolbar.frame.origin.y + viewToolbar.frame.size.height;
    [viewNoComment setFrame:nRect];
    [staduimScrollView addSubview:viewNoComment];
}


- (void)hideKeyboard {
    [tfComment resignFirstResponder];
    [btnHideKeyboard removeFromSuperview];
    btnHideKeyboard = nil;
}


#pragma mark - UITextFiedDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    //    rectInput = viewInput.frame;
    //    [viewInput removeFromSuperview];
    //    [accessoryView addSubview:viewInput];
    //    [viewInput setFrame:CGRectMake(0, 0, rectInput.size.width, rectInput.size.height)];
    
    [textField.inputAccessoryView addSubview:accessoryView];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    //    [viewInput removeFromSuperview];
    //    [viewButtom addSubview:viewInput];
    //    [viewInput setFrame:rectInput];
    [accessoryView removeFromSuperview];
}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [commentArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CircleCommentCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"CircleCommentCell" owner:self options:nil] objectAtIndex:0];
    }
    
    if([cell respondsToSelector:@selector(setDataInfo:)]){
        [cell performSelector:@selector(setDataInfo:) withObject:[commentArray objectAtIndex:indexPath.row]];
    }
    if([cell respondsToSelector:@selector(setDelegate:)]){
        [cell performSelector:@selector(setDelegate:) withObject:self];
    }
    
    [cell setTag:indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
     return [self getCellHeightWithContent:[commentArray objectAtIndex:indexPath.row]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}


@end
